package com.ws.shop.action.admin;

import java.io.File;
import java.text.NumberFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ws.shop.bean.FileDir;
import com.ws.shop.entity.Accessory;
import com.ws.shop.service.AccessoryService;
import com.ws.shop.util.DateUtil;
import com.ws.shop.util.RequestUtil;

@Controller
@RequestMapping(value="/admin/accessory/*")
public class AccessoryAction extends BaseAdminAction{
	private static Logger log = Logger.getLogger(AccessoryAction.class);
	@Resource(name="fileDir")
	private FileDir fileDir;
	long maxSize = 2097152;//最大2M
	private static int fileSeq = 0;
	public static String SAVE_IMAG_URL = "http://localhost:8080/accessory/";
	@Autowired
	private AccessoryService accessoryService;
	
	@RequestMapping(value="upload.jhtml",method=RequestMethod.POST)
	public String upload(HttpServletRequest request,HttpServletResponse response) throws FileUploadException{
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		List<FileItem> items = (List<FileItem>)upload.parseRequest(request);
		Iterator<FileItem> itr = items.iterator();
		FileItem item = null;
		while (itr.hasNext()) {
			item = itr.next();
			String fileName = item.getName();
			if (!item.isFormField()) {
				//检查文件大小
				if(item.getSize() > maxSize){
					return this.ajaxJsonErrorMessage(response, "上传文件大小超过最大限制。");
				}
				//检查扩展名
				String fileExt = "";
				if(fileName.indexOf(".") >= 0)
					fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
				String newFileName = getFileSeq() + "." + fileExt;
				try{
					File uploadedFile = new File(fileDir.getUploadSave(), newFileName);
					item.write(uploadedFile);
				}catch(Exception e){
					return this.ajaxJsonErrorMessage(response, "上传文件失败");
				}
				Accessory accessory = new Accessory(0, "img", "", newFileName, item.getSize(),
						newFileName, null);
				try{
					Object[] result = accessoryService.saveOrUpdate(accessory);
					if(0 != (Integer)result[0]){
						return this.ajaxJsonErrorMessage(response, (String)result[1]);
					}
					Map<String,String> jsonMap = new HashMap<String,String>();
					jsonMap.put(STATUS, "success");
					jsonMap.put(MESSAGE, "上传成功");
					jsonMap.put("saveURL", SAVE_IMAG_URL+newFileName);
					jsonMap.put("id", (String)result[1]);
					return this.ajaxJson(response, jsonMap);
				}catch(Exception e){
					log.error("保存文件信息失败",e);
					return this.ajaxJsonErrorMessage(response, "系统异常，请稍后再试");
				}
			}
		}
		return this.ajaxJsonErrorMessage(response, "没有选中要上传的文件");
	}
	
	@RequestMapping(value="delete.jhtml",method=RequestMethod.POST)
	public String delete(HttpServletRequest request,HttpServletResponse response){
		int id = RequestUtil.getIntParameter(request, "id", 0);
		if(id <= 0){
			return this.ajaxJsonErrorMessage(response, "您要删除的文件不存在");
		}
		try{
			accessoryService.deleteById(id);
			return this.ajaxJsonSuccessMessage(response, "删除成功");
		}catch(Exception e){
			log.error("删除失败ID="+id,e);
			return this.ajaxJsonErrorMessage(response, "删除失败");
		}
	}
	
	public synchronized static String getFileSeq() {
		if (fileSeq < 999) {
			fileSeq++;
		} else {
			fileSeq = 1;
		}
		// 数字格式化
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMinimumIntegerDigits(3);
		nf.setGroupingUsed(false);
		return DateUtil.dateToString(new Date(), DateUtil.YYYYMMDDHHMMSS)
				+ nf.format(fileSeq);
	}
}
